$(function () {
    document.body.setAttribute("class", "bg-" + sessionStorage.getItem("bg"));


    function arrayBufferToBase64(buffer) {
        let binary = '';
        let bytes = new Uint8Array(buffer);
        let len = bytes.byteLength;
        for (let i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }

    //
    function skip() {
        window.location.href = "/userinfo/" + sessionStorage.getItem("uid");
    }

    //显示用户头像
    function showuserpic() {
        let pic = sessionStorage.getItem("pic");
        let img = document.createElement("img");
        img.src = "data:image/jpeg;base64," + pic;
        img.width = 45;
        img.height = 45;
        $("#image").html(img);
        $("#username").text(sessionStorage.getItem("username"));
    }

    let webSocket = null;
    if ("WebSocket" in window) {
        webSocket = new WebSocket("ws://localhost:8080/websocket/" + sessionStorage.getItem("uid")+"&view");
    } else {
        alert("浏览器不支持webSocket！");
    }

    webSocket.onopen = function () {
        console.log("连接成功");
    };
    //刷新div

    let users;
    let unreadmess;
    let historyList;
    let likeList;
    let setting;
    let messagebox;

    webSocket.onmessage = function (event) {
        let obj = JSON.parse(event.data);

        let type = obj.type;
        //登录测试

        //console.log(sessionStorage.getItem(sessionStorage.getItem("username")));
        let tokendata = obj.tokendata;
        //console.log(tokendata);
        for (let i = 0; i < tokendata.length; i++) {
            if (tokendata[i].username === sessionStorage.getItem("username")) {
                if (tokendata[i].token !== sessionStorage.getItem("token")) {
                    alert("用户已在异地登录，请重新登录!");
                    window.location.href = "/login";
                }
            }
        }


        //console.log(type[0].type);
        //以下为各个模块的内容

        switch (type[0].type) {
            case "useronline":
                users = obj.useronline;
                //     sessionStorage.removeItem("users");
                //     sessionStorage.setItem("users", JSON.stringify(obj.useronline));
                break;
            case "messageState":
                sessionStorage.removeItem("unreadmess");
                sessionStorage.setItem("unreadmess", JSON.stringify(obj.messageState));
                break;
            case "historyList":
                sessionStorage.removeItem("historyList");
                sessionStorage.setItem("historyList", JSON.stringify(obj.historyList));
                break;
            case "followList":
                sessionStorage.removeItem("likeList");
                sessionStorage.setItem("likeList", JSON.stringify(obj.followList));
                break;
            case "setting":
                sessionStorage.removeItem("setting");
                sessionStorage.setItem("setting", JSON.stringify(obj.setting));
                break;
            case "messageBox":
                sessionStorage.removeItem("messagebox");
                sessionStorage.setItem("messagebox", JSON.stringify(obj.messageBox));
                messagebox = JSON.parse(sessionStorage.getItem("messagebox"));
                if (users != null) {
                    chattingbox(users, messagebox);
                }

                break;
        }

        console.log(obj);


        if ((users != null)
            && (sessionStorage.getItem("unreadmess") != null)
            && (sessionStorage.getItem("historyList") != null)
            && (sessionStorage.getItem("likeList") != null)
            && (sessionStorage.getItem("setting") != null)
            && (sessionStorage.getItem("messagebox") != null)) {
            //users = obj.useronline;
            //let users = JSON.parse(sessionStorage.getItem("users"));
            unreadmess = JSON.parse(sessionStorage.getItem("unreadmess"));
            historyList = JSON.parse(sessionStorage.getItem("historyList"));
            likeList = JSON.parse(sessionStorage.getItem("likeList"));
            setting = JSON.parse(sessionStorage.getItem("setting"));
            messagebox = JSON.parse(sessionStorage.getItem("messagebox"));
            showuser(users, unreadmess, setting);
            chathisory(users, unreadmess, historyList, setting);
            showhistory(setting);
            likeuser(users, unreadmess, likeList, setting);
            chatsetting(setting);
            showuserpic();
            chattingbox(users, messagebox);
        }
    };

    //鼠标事件相关
    function ctolike(oid) {
        let status = document.getElementById("s" + oid);
        status.setAttribute("class", "");
        status.setAttribute("style", "position: absolute;right: 0px;top: 0px;");
        status.innerHTML = "<button type=\"button\" class='btn btn-blue'>关注</button>";
        status.onclick = function () {
            dolike(oid);
        }
    }

    function ctostatus(oid) {
        let like = document.getElementById("s" + oid);
        like.innerHTML = '';
        like.setAttribute("class", "badge badge-outline status")
    }

    function dolike(oid) {
        let uid = sessionStorage.getItem("uid")
        $.ajax({
            type: "GET",
            url: "/changeFollow/" + uid + "&" + oid,
            async: false,
            success: function (result) {
            },
            error: function (errorMsg) {
                alert("关注失败");
            }
        });
    }

    //显示在线用户
    function showuser(users, unreadmess, setting) {
        let menuuser = document.getElementById("mmenu-users");
        menuuser.innerHTML = '';
        let title = document.createElement("h5");
        let titlecss = document.createElement("strong");
        let titleoff = document.createElement("h5");
        let titlecssoff = document.createElement("strong");
        let ulonline = document.createElement("ul");
        let uloffline = document.createElement("ul");
        //未读消息个数显示
        let messnum = document.getElementById("currmessnum");

        titlecss.innerText = '在线用户';
        title.appendChild(titlecss);
        titlecssoff.innerText = '离线用户';
        titleoff.appendChild(titlecssoff);
        titleoff.setAttribute("id", "titleoff");
        ulonline.setAttribute("class", "users-list");
        uloffline.setAttribute("class", "users-list");
        uloffline.setAttribute("id", "offlineUl");
        if (setting.offline == 0) {
            titleoff.style.visibility = "hidden";
            uloffline.style.visibility = "hidden";
        }
        for (let i = 0; i < users.length; i++) {
            if (users[i].username != sessionStorage.getItem("username")) {
                if (users[i].online == 1) {
                    let li = document.createElement("li");
                    let media = document.createElement("div");
                    let mediaobject = document.createElement("a");
                    let mediaobjectimg = document.createElement("img");
                    let mediabody = document.createElement("div");
                    let username = document.createElement("h6");
                    let email = document.createElement("small");
                    let userstatus = document.createElement("span");
                    let userinbox = document.getElementById("user-inbox")
                    li.setAttribute("class", "online");
                    //显示跳转or添加
                    li.onmouseenter = function () {
                        ctolike(users[i].id);
                    }
                    li.onmouseleave = function () {
                        ctostatus(users[i].id);
                    }
                    media.setAttribute("class", "media");
                    mediaobject.setAttribute("class", "pull-left profile-photo");

                    mediaobject.onclick = function () {
                        openchatting(users[i].id, 520, 650);
                    };
                    mediaobjectimg.setAttribute("class", "media-object");
                    mediaobjectimg.src = "data:image/jpeg;base64," + arrayBufferToBase64(users[i].pic);
                    mediabody.setAttribute("class", "media-body");
                    username.setAttribute("class", "media-heading");
                    username.innerText = users[i].username;
                    email.innerText = users[i].email;
                    userstatus.setAttribute("class", "badge badge-outline status");
                    userstatus.setAttribute("id", "s" + users[i].id);
                    mediabody.appendChild(username);
                    mediabody.appendChild(email);
                    mediabody.appendChild(userstatus);
                    mediaobject.appendChild(mediaobjectimg);
                    media.appendChild(mediaobject);
                    //消息未读提示,及未读消息个数
                    let totalmessnum = 0;
                    for (let j = 0; j < unreadmess.length; j++) {
                        totalmessnum = totalmessnum + unreadmess[j].count;
                        if (users[i].id == unreadmess[j].fromId) {
                            let mediamess = document.createElement("span");
                            mediamess.setAttribute("class", "badge badge-red unread");
                            mediamess.setAttribute("name", "redunread");
                            if (setting.unread == 0) {
                                mediamess.style.visibility = "hidden";
                            }
                            if (setting.unread == 1) {
                                mediamess.style.visibility = "visible";
                            }
                            mediamess.innerText = unreadmess[j].count;
                            media.appendChild(mediamess);
                        }
                    }
                    userinbox.innerText = totalmessnum;
                    messnum.innerText = totalmessnum;//未读个数
                    media.appendChild(mediabody);
                    li.appendChild(media);
                    ulonline.appendChild(li);
                }
                if (users[i].online == 0) {
                    let li = document.createElement("li");
                    let media = document.createElement("div");
                    let mediaobject = document.createElement("a");
                    let mediaobjectimg = document.createElement("img");
                    let mediabody = document.createElement("div");
                    let username = document.createElement("h6");
                    let email = document.createElement("small");
                    let userstatus = document.createElement("span");
                    li.setAttribute("class", "offline");
                    li.onmouseenter = function () {
                        ctolike(users[i].id);
                    }
                    li.onmouseleave = function () {
                        ctostatus(users[i].id);
                    }
                    media.setAttribute("class", "media");
                    mediaobject.setAttribute("class", "pull-left profile-photo");
                    mediaobject.onclick = function () {
                        openchatting(users[i].id, 520, 650)
                    };
                    mediaobjectimg.setAttribute("class", "media-object");
                    mediaobjectimg.src = "data:image/jpeg;base64," + arrayBufferToBase64(users[i].pic);
                    mediabody.setAttribute("class", "media-body");
                    username.setAttribute("class", "media-heading");
                    username.innerText = users[i].username;
                    email.innerText = users[i].email;
                    userstatus.setAttribute("class", "badge badge-outline status");
                    userstatus.setAttribute("id", "s" + users[i].id);
                    mediabody.appendChild(username);
                    mediabody.appendChild(email);
                    mediabody.appendChild(userstatus);
                    mediaobject.appendChild(mediaobjectimg);
                    media.appendChild(mediaobject);
                    if (setting.unread == 1) {
                        for (let j = 0; j < unreadmess.length; j++) {
                            if (users[i].id == unreadmess[j].fromId) {
                                let mediamess = document.createElement("span");
                                mediamess.setAttribute("name", "redunread");
                                mediamess.setAttribute("class", "badge badge-red unread");
                                mediamess.innerText = unreadmess[j].count;
                                media.appendChild(mediamess);
                            }
                        }
                    }
                    media.appendChild(mediabody);
                    li.appendChild(media);
                    uloffline.appendChild(li);
                }
            } else {
                sessionStorage.removeItem("userpic");
                sessionStorage.setItem("userpic", arrayBufferToBase64(users[i].pic))
            }
        }

        menuuser.appendChild(title);
        menuuser.appendChild(ulonline);
        menuuser.appendChild(titleoff);
        menuuser.appendChild(uloffline);
    }

    //显示聊天历史记录
    function chathisory(users, unreadmess, historyList, setting) {
        let menuhistory = document.getElementById("mmenu-history");
        let chathitorybar = document.createElement("h5");
        let historyul = document.createElement("ul");
        chathitorybar.innerText = "聊天历史";
        historyul.setAttribute("class", "history-list");
        for (let i = 0; i < historyList.length; i++) {
            for (let j = 0; j < users.length; j++) {
                if (historyList[i].uid == users[j].id) {
                    let historyli = document.createElement("li");
                    let historydiv = document.createElement("div");
                    let historya = document.createElement("a");
                    let historyimg = document.createElement("img");
                    let historymediabody = document.createElement("div");
                    let historyname = document.createElement("h6");
                    let historymess = document.createElement("small");
                    let historystatus = document.createElement("span");
                    historydiv.setAttribute("class", "media");
                    historya.setAttribute("class", "pull-left profile-photo");
                    historya.onclick = function () {
                        openchatting(users[j].id, 520, 650);
                    };
                    historyimg.setAttribute("class", "media-object");
                    historyimg.src = "data:image/jpeg;base64," + arrayBufferToBase64(users[j].pic);
                    historymediabody.setAttribute("class", "media-body");
                    historyname.setAttribute("class", "media-heading");
                    historyname.innerText = users[j].username;
                    historymess.innerText = historyList[i].text;
                    historystatus.setAttribute("class", "badge badge-outline status")
                    if (users[j].online == 1) {
                        historyli.setAttribute("class", "online");
                    } else {
                        historyli.setAttribute("class", "offline");
                    }
                    historymediabody.appendChild(historyname);
                    historymediabody.appendChild(historymess);
                    historymediabody.appendChild(historystatus);
                    historya.appendChild(historyimg);
                    if (setting.unread == 1) {
                        for (let z = 0; z < unreadmess.length; z++) {
                            if (historyList[i].uid == unreadmess[z].fromId) {
                                let mediamess = document.createElement("span");
                                mediamess.setAttribute("class", "badge badge-red unread");
                                mediamess.setAttribute("name", "redunread");
                                mediamess.innerText = unreadmess[z].count;
                                historydiv.appendChild(mediamess);
                            }
                        }
                    }
                    historydiv.appendChild(historya);
                    historydiv.appendChild(historymediabody);
                    historyli.appendChild(historydiv);
                    historyul.appendChild(historyli);
                }
            }
        }
        menuhistory.innerHTML = '';
        menuhistory.appendChild(chathitorybar);
        menuhistory.appendChild(historyul);

    }

    //关注页面
    function likeuser(users, unreadmess, likeList, setting) {
        let menulike = document.getElementById("mmenu-friends");
        let likebar = document.createElement("h5");
        let likeul = document.createElement("ul");
        likebar.innerText = "关注列表";
        likeul.setAttribute("class", "favourite-list");
        for (let i = 0; i < likeList.length; i++) {
            for (let j = 0; j < users.length; j++) {
                if (likeList[i].uid == users[j].id) {
                    let likeli = document.createElement("li");
                    let likediv = document.createElement("div");
                    let likea = document.createElement("a");
                    let likeimg = document.createElement("img");
                    let likemediabody = document.createElement("div");
                    let likename = document.createElement("h6");
                    let likemess = document.createElement("small");
                    let likestatus = document.createElement("span");
                    likediv.setAttribute("class", "media");
                    likea.setAttribute("class", "pull-left profile-photo");
                    likea.onclick = function () {
                        openchatting(users[j].id, 520, 650);
                    };
                    likeimg.setAttribute("class", "media-object");
                    likeimg.src = "data:image/jpeg;base64," + arrayBufferToBase64(users[j].pic);
                    likemediabody.setAttribute("class", "media-body");
                    likename.setAttribute("class", "media-heading");
                    likename.innerText = users[j].username;
                    likemess.innerText = users[j].email;
                    likestatus.setAttribute("class", "badge badge-outline status")
                    if (users[j].online == 1) {
                        likeli.setAttribute("class", "online");
                    } else {
                        likeli.setAttribute("class", "offline");
                    }
                    likemediabody.appendChild(likename);
                    likemediabody.appendChild(likemess);
                    likemediabody.appendChild(likestatus);
                    likea.appendChild(likeimg);
                    if (setting.unread == 1) {
                        for (let z = 0; z < unreadmess.length; z++) {
                            if (likeList[i].uid == unreadmess[z].fromId) {
                                let mediamess = document.createElement("span");
                                mediamess.setAttribute("class", "badge badge-red unread");
                                mediamess.setAttribute("name", "redunread");
                                mediamess.innerText = unreadmess[z].count;
                                likediv.appendChild(mediamess);
                            }
                        }
                    }
                    likediv.appendChild(likea);
                    likediv.appendChild(likemediabody);
                    likeli.appendChild(likediv);
                    likeul.appendChild(likeli);
                }
            }
        }
        menulike.innerHTML = '';
        menulike.appendChild(likebar);
        menulike.appendChild(likeul);
    }

    //设置相关
    function chatsetting(setting) {
        let showoffline = document.getElementById("show-offline");
        let showhistory = document.getElementById("show-history");
        let showunread = document.getElementById("show-unread");

        showoffline.onclick = function () {
            changesetting("offline");
            if (setting.offline == 1) {
                setting.offline = 0;
                document.getElementById("offlineUl").style.visibility = "hidden";
                document.getElementById("titleoff").style.visibility = "hidden";
            } else {
                setting.offline = 1;
                document.getElementById("offlineUl").style.visibility = "visible";
                document.getElementById("titleoff").style.visibility = "visible";
            }
        }
        showhistory.onclick = function () {
            changesetting("history");
            if (setting.history == 0) {
                setting.history = 1;
                document.getElementById("historyMenu").style.visibility = "visible";
            } else {
                setting.history = 0;
                document.getElementById("historyMenu").style.visibility = "hidden";
            }
        }
        showunread.onclick = function () {
            changesetting("unread");
            if (setting.unread == 0) {
                setting.unread = 1;
                let list = document.getElementsByName("redunread");
                for (i in list) {
                    list[i].style = "visibility:visible";
                }
            } else {
                setting.unread = 0;
                let list = document.getElementsByName("redunread")
                for (i in list) {
                    list[i].style = "visibility:hidden";
                }
            }
        }

        if (setting.offline == 1) {
            showoffline.checked = true;
        } else {
            showoffline.checked = false;
        }

        if (setting.history == 1) {
            showhistory.checked = true;
        } else {
            showhistory.checked = false;
        }

        if (setting.unread == 1) {
            showunread.checked = true;
        } else {
            showunread.checked = false;
        }
    }

    function changesetting(settingtype) {
        let uid = sessionStorage.getItem("uid")
        $.ajax({
            type: "GET",
            url: "/changeSetting/" + uid + "&" + settingtype,
            async: false,
            success: function (result) {
                console.log(settingtype + "更改");
            },
            error: function (errorMsg) {
                alert("设置失败");
            }
        });
    }

    function showhistory(setting) {
        if (setting.history == 0) {
            // let tab = document.getElementById("mm-m0-p0");
            // let lilist = tab.querySelectorAll("li");
            // if (lilist.length==4) {
            //     lilist[1].remove();
            // }
            document.getElementById("historyMenu").style.visibility = "hidden";
        } else {
            document.getElementById("historyMenu").style.visibility = "visible";
        }
    }

    //消息盒子
    function chattingbox(users, messagebox) {
        let messageboxul = document.getElementById("messagebox");
        //设置背景颜色
        let bgmap = {};
        bgmap[0] = "orange";
        bgmap[1] = "green";
        bgmap[2] = "cyan";
        bgmap[3] = "red";
        bgmap[4] = "orange";
        messageboxul.innerHTML = '';
        messageboxul.setAttribute("class", "dropdown-menu wider arrow nopadding messages");
        for (let i = 0; i < messagebox.length; i++) {
            for (let j = 0; j < users.length; j++) {
                if (messagebox[i].id == users[j].id) {
                    let messageboxli = document.createElement("li");
                    let messageboxa = document.createElement("a");
                    messageboxa.setAttribute("class", bgmap[i]);
                    //点击事件
                    messageboxa.onclick = function () {
                        openchatting(users[j].id, 520, 650);
                    };
                    let messageboxdivimg = document.createElement("div");
                    messageboxdivimg.setAttribute("class", "profile-photo");
                    let messageboximg = document.createElement("img");
                    //添加头像
                    messageboximg.src = "data:image/jpeg;base64," + arrayBufferToBase64(users[j].pic);
                    let messageboxdivmessinfo = document.createElement("div");
                    messageboxdivmessinfo.setAttribute("class", "message-info");
                    //发送者
                    let messageboxusername = document.createElement("span");
                    messageboxusername.setAttribute("class", "sender");
                    messageboxusername.innerText = users[j].username;
                    //消息时间
                    let messageboxmesstime = document.createElement("span");
                    messageboxmesstime.setAttribute("class", "time");
                    messageboxmesstime.innerText = formatDate(messagebox[i].time) + " 前";
                    //消息内容
                    let messageboxmesscontent = document.createElement("div");
                    messageboxmesscontent.setAttribute("class", "message-content");
                    messageboxmesscontent.innerText = messagebox[i].text;
                    messageboxdivmessinfo.appendChild(messageboxusername);
                    messageboxdivmessinfo.appendChild(messageboxmesstime);
                    messageboxdivmessinfo.appendChild(messageboxmesscontent);
                    messageboxdivimg.appendChild(messageboximg);
                    messageboxa.appendChild(messageboxdivimg);
                    messageboxa.appendChild(messageboxdivmessinfo);
                    messageboxli.appendChild(messageboxa);
                    messageboxul.appendChild(messageboxli);
                }
            }
        }

    }

    function formatDate(date, format) {
        if (!date) return;
        if (!format) format = "HH:mm:ss";
        switch (typeof date) {
            case "string":
                date = new Date(date.replace(/-/, "/"));
                break;
            case "number":
                date = new Date(date);
                break;
        }
        if (!date instanceof Date) return;
        var dict = {
            "yyyy": date.getFullYear(),
            "M": date.getMonth() + 1,
            "d": date.getDate(),
            "H": date.getHours(),
            "m": date.getMinutes(),
            "s": date.getSeconds(),
            "MM": ("" + (date.getMonth() + 101)).substr(1),
            "dd": ("" + (date.getDate() + 100)).substr(1),
            "HH": ("" + (date.getHours() + 92)).substr(1),
            "mm": ("" + (date.getMinutes() + 100)).substr(1),
            "ss": ("" + (date.getSeconds() + 100)).substr(1)
        };
        return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?)/g, function () {
            return dict[arguments[0]];
        });
    }

    //关闭按钮调用函数
    function clo() {
        webSocket.close(3000, "强制关闭");
    }

    window.onbeforeunload = function () {
        clo();
    };

    function openchatting(oid, iWidth, iHeight) {
        let url = "chat1/" + sessionStorage.getItem("uid") + '&' + oid;
        //获得窗口的垂直位置
        let iTop = (window.screen.availHeight - 30 - iHeight) / 2;
        //获得窗口的水平位置
        let iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
        window.open(url, "", 'height=' + iHeight + ',innerHeight=' + iHeight +
            ', width = ' + iWidth + ', innerWidth = ' + iWidth + ', top = ' + iTop + ', left = ' + iLeft +
            ', status = no, toolbar = no, menubar = no, location = no, resizable = no, scrollbars = 0, titlebar = no');
    }

});

function bgchange(bg) {
    let uid=parseInt(sessionStorage.getItem("uid"));
    $.ajax({
        type: "GET",
        url: "/bgchange/" + uid + "&" + bg,
        async: false,
        success: function (result) {
            sessionStorage.setItem("bg",bg);
        },
        error: function (errorMsg) {
            alert("修改失败");
        }
    });
}